const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📋 获取施工队伍申请列表')
  
  try {
    const { status = null, page = 1, pageSize = 10 } = event
    
    // 计算跳过的记录数
    const skip = (page - 1) * pageSize
    
    // 构建查询条件
    let whereCondition = {}
    if (status && status !== 'all') {
      whereCondition.auditStatus = status
    }
    
    // 获取总数
    const countResult = await db.collection('construction_teams')
      .where(whereCondition)
      .count()
    
    const totalCount = countResult.total
    
    // 获取申请列表
    let query = db.collection('construction_teams')
      .where(whereCondition)
    
    // 根据状态决定排序方式
    if (status === 'pending') {
      // 待审核按提交时间升序（先提交的先审核）
      query = query.orderBy('submitTime', 'asc')
    } else {
      // 其他状态按审核时间降序（最新审核的在前）
      query = query.orderBy('auditTime', 'desc')
    }
    
    const applicationsResult = await query
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 处理申请数据，只返回必要字段
    const applications = applicationsResult.data.map(app => ({
      _id: app._id,
      id: app.id,
      openid: app.openid,
      name: app.name,
      type: app.type,
      typeName: app.typeName,
      phone: app.phone,
      location: app.location,
      category: app.category,
      categoryName: app.categoryName,
      experience: app.experience,
      description: app.description,
      specialties: app.specialties || [],
      certifications: app.certifications || [],
      avatar: app.avatar,
      auditStatus: app.auditStatus,
      canReceiveOrders: app.canReceiveOrders,
      submitTime: app.submitTime,
      auditTime: app.auditTime,
      auditReason: app.auditReason,
      auditBy: app.auditBy,
      createTime: app.createTime,
      // 个人师傅特有字段
      realName: app.realName,
      idCard: app.idCard,
      // 公司特有字段
      companyName: app.companyName,
      businessLicense: app.businessLicense,
      legalRepresentative: app.legalRepresentative,
      registeredCapital: app.registeredCapital,
      companyAddress: app.companyAddress
    }))
    
    console.log(`✅ 获取到 ${applications.length} 个申请记录`)
    
    return {
      success: true,
      data: {
        applications: applications,
        pagination: {
          page: page,
          pageSize: pageSize,
          totalCount: totalCount,
          totalPages: Math.ceil(totalCount / pageSize),
          hasMore: skip + applications.length < totalCount
        }
      }
    }
    
  } catch (error) {
    console.error('❌ 获取申请列表失败:', error)
    return {
      success: false,
      error: error.message || '获取申请列表失败'
    }
  }
}
